<?php
/**
 * Created by PhpStorm.
 * User: rain
 * Date: 2018/4/7
 * Time: 下午1:40
 */

namespace App\Utils;

use Illuminate\Support\Facades\DB;

class GeneratorModelUtil
{
    /**
     * 指定表生成model
     * @param array $tables
     */
    public static function generatorModels($tables = [])
    {
        if (empty($tables)){
            $result = DB::select('show tables');
            foreach($result as $value){
                $value = (array)$value;
                $tables[] = $value['Tables_in_' . env('DB_DATABASE', '')];
            }
        }

        foreach($tables as $tableName){
            if (strpos($tableName, 'admin') !== false || strpos($tableName, 'migrations') !== false
                || strpos($tableName, 'password_resets') !== false){
                //管理后台的忽略
                continue;
            }

            $className = ucfirst(preg_replace_callback('/_+([a-z])/', function ($matches){
                return strtoupper($matches[1]);
            }, $tableName));

            $columnInfos = DB::select("desc $tableName");
            $columns = [];
            foreach($columnInfos as $columnInfo){
                $columnInfo = (array)$columnInfo;
                $filed = $columnInfo['Field'];
                $type = strpos($columnInfo['Type'], 'int') !== false ? 'integer' : 'string';
                $columns[] = " * @property $type \$$filed";
            }

            $columns = implode("\n", $columns);

            $phpStr = <<<STR
<?php
/**
 * Created by PhpStorm
 * User: rain
 * Date: 2018/12/26
 * Time: 下午5:23
 */

namespace App\Models;

use Illuminate\Database\Eloquent\Model;


/**
 * Class $className
$columns
 * @package App\Models
 */
class $className extends Model
{
    protected \$table = '$tableName';

}
STR;
            $filePath = app_path("Models/$className.php");
            if (file_exists($filePath)){
                echo $className . '文件已存在', PHP_EOL;
            }else{
                echo file_put_contents($filePath, $phpStr);
            }

        }

    }

}